package com.hfi.security.core.aspect;

import com.hfi.security.core.exception.ErrorCode;
import com.hfi.security.core.support.Response;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

/**
 * @author ChangLiang
 * @date 2019/9/5
 */
@Component
@Aspect
public class AuthTokenAspect {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /// @Around是可以改变controller返回值的
    @Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        // 放行
        Response response = new Response();
        Object proceed = pjp.proceed();
        if (proceed != null) {
            ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>)proceed;
            OAuth2AccessToken body = responseEntity.getBody();
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                response.setErrorcode(ErrorCode.OK.value);
                response.setValue(ErrorCode.OK.memo);
                response.setData(body);
            } else {
                logger.error("error:{}", responseEntity.getStatusCode().toString());
                response.setErrorcode(ErrorCode.ERROR.value);
                response.setValue("获取授权码失败");
            }
        }
        return ResponseEntity
                .status(200)
                .body(response);
    }
}
